<template>
  <div style="border: 1px solid #ccc">
    <Toolbar
      style="border-bottom: 1px solid #ccc"
      :editor="editorRef"
      :defaultConfig="toolbarConfig"
      :mode="mode"
    />
    <Editor
      style="height: 810px; overflow-y: hidden"
      v-model="valueHtml"
      :defaultConfig="editorConfig"
      :mode="mode"
      @onCreated="handleCreated"
      @onBlur="handleBlur"
    />
  </div>
</template>

<script setup lang="ts">
import axios from 'axios'
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { onBeforeUnmount, ref, shallowRef, onMounted, nextTick } from 'vue'
// @ts-ignore
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { createEditor } from '@wangeditor/editor'
import { MyStorage } from '@/utils/utils'
import { useRoute, useRouter } from 'vue-router'
import { useWordStore } from '@/store/wordStore'
import { useUserStore } from '@/store/userStore'

const route = useRoute()
const router = useRouter()

const userStore = useUserStore()
const wordStore = useWordStore()

const mode = 'default' // 或 'simple'
// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()
// 内容 HTML
const valueHtml = ref('')
// 配置
const toolbarConfig = {}

const editorConfig = {
  placeholder: '<h1>失去焦点自动更新内容</h1>',
  // 配置富文本图片上传地址
  MENU_CONF: {
    uploadImage: {
      fieldName: 'file',
      // 上传的图片类型
      allowedFileTypes: ['image/*'],
      // server: '/api/user/wordfile',

      onSuccess(file: File, res: any) {
        // TS 语法
        // onSuccess(file, res) {          // JS 语法
        console.log(`${file.name} 上传成功`, res)
      },
      // 自定义上传，配置的service上传出问题可以使用如下方法
      customUpload(file: any, insertFn: any) {
        let fm = new FormData()
        fm.append('file', file)
        axios
          .post('/api/user/wordfile', fm, {
            headers: {
              Authorization: MyStorage.get('token')
            }
          })
          .then((response: any) => {
            // 将图片插入到编辑器中
            insertFn(response.data.data.url, '使用说明', response.data.data.url)
          })
      }
    }
  }
}

const handleCreated = (editor: any) => {
  editorRef.value = editor // 记录 editor 实例，重要！
  if (route.query?.text) {
    editor.setHtml(route.query.text)
  }
}

// 失去焦点的时候自动更新内容
const handleBlur = async (editor: any) => {
  // console.log(editor.getHtml()) 获取富文本编辑中的html结构
  if (route.query.textid) {
    // 代表编辑文章
    if (editor.isEmpty()) {
      // 判断当前是否为空，若为空则不执行
      return
    }
    let code = await wordStore.updateInfo('/tale/talelist', route.query.textid, {
      text: editor.getHtml()
    })
    if (code === 200) {
      // 清除内容
      editor.clear()
      // 跳转列表展示
      router.push({
        path: '/main/tale/talelist'
      })
    }
  } else {
    if (editor.isEmpty()) {
      // 判断当前是否为空，若为空则不执行
      return
    }
    // 代表创建文章
    let code = await wordStore.addWordItemAction('/tale/talelist', {
      username: userStore.userInfoDetail?.username,
      text: editor.getHtml()
    })
    if (code === 200) {
      // 清除内容
      editor.clear()
      // 跳转列表展示
      router.push({
        path: '/main/tale/talelist'
      })
    }
  }
}

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})
</script>

<style lang="scss" scoped></style>
